<template>
  <el-form
      ref="formRef"
      :model="form"
      label-width="100px"
      style="text-align: center;padding-bottom:10px"
  >
    <el-upload
        :headers="headers"
         class="avatar-uploader"
        :action="avatarUploadUrl"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
      <el-icon v-else class="avatar-uploader-icon">
        <Plus/>
      </el-icon>
    </el-upload>
<!--    <el-button @click="handleConfirm">确认更换</el-button>-->
  </el-form>
</template>
<script setup lang="ts">
import {defineProps, ref} from "vue";
import {getServerUrl} from "@/utils/request";
import {ElMessage, FormInstance} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import store from "@/store";
import {updateAvatar} from "@/api/user";

const props = defineProps(
    {
      user: {
        type: Object,
        required: true
      }
    }
)
const headers = ref({Authorization: store.getters.GET_TOKEN})
interface Form {
  id: number,
  avatar: string
}

const form = ref<Form>({
  id: -1,
  avatar: ''
})
const avatarUploadUrl=ref(getServerUrl()+'/user/upload/avatar')

const formRef = ref<FormInstance>()
const imageUrl = ref("")
form.value = props.user as Form;
console.log(form.value)
imageUrl.value = getServerUrl() + '/image/userAvatar/' + form.value.avatar;
const handleAvatarSuccess =async (res: any) => {
  const data = res.data;
  if (res.code != 200) {
    ElMessage.error(res.msg);
    return false;
  }else {
    ElMessage.success("上传成功！")
    imageUrl.value = getServerUrl() +'/'+ data.src
    form.value.avatar = data.title;
    await handleConfirm()
  }
}
const beforeAvatarUpload = (file: any) => {
  //判断是否格式为图片
  const isJPG = file.type === 'image/jpeg'
  const isLt2M = file.size / 1024 / 1024 < 5
  if (!isJPG) {
    ElMessage.error('图片必须是jpg格式')
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过5M!')
  }
  return isJPG && isLt2M
}
const handleConfirm = async () => {
  const result: any = await updateAvatar(form.value);
  const data = result.data;
  if (data.code == 200) {
    ElMessage.success("执行成功！")
    store.commit("SET_USER_INFO", form.value)
  } else {
    ElMessage.error(data.msg);
  }
}
</script>
<style scoped lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>